package com.xmmj.baselibrary.utils.viewadapter.text

import android.graphics.Color
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.TextWatcher
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.util.TypedValue
import android.widget.TextView
import androidx.databinding.BindingAdapter

@BindingAdapter(value = ["android:text"], requireAll = false)
fun setText(textView: TextView, text: Int) {
    textView.setText(text)
}

@BindingAdapter(value = ["android:drawableStart"], requireAll = false)
fun setDrawableStart(textView: TextView, drawableStart: Int) {
    textView.setCompoundDrawablesRelativeWithIntrinsicBounds(drawableStart, 0, 0, 0)
}

@BindingAdapter(value = ["android:textSize"], requireAll = false)
fun setTextSize(textView: TextView, textSize: Float) {
    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, textSize)
}

@BindingAdapter(value = ["textWatcher"], requireAll = false)
fun addTextChangedListener(textView: TextView, textWatcher: TextWatcher) {
    textView.addTextChangedListener(textWatcher)
}

@BindingAdapter(value = ["spanStart", "spanEnd", "spanColor", "spanClick"], requireAll = false)
fun setColorSpan(
    textView: TextView,
    spanStart: Int,
    spanEnd: Int,
    spanColor: Int,
    spanClick: ClickableSpan?
) {
    val spannableBuilder = SpannableStringBuilder(textView.text)
    spanClick?.let {
        spannableBuilder.setSpan(it, spanStart, spanEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    }
    spanColor.let {
        spannableBuilder.setSpan(
            ForegroundColorSpan(textView.context.resources.getColor(it)),
            spanStart,
            spanEnd,
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )
    }
    textView.movementMethod = LinkMovementMethod.getInstance()
    textView.text = spannableBuilder
}

@BindingAdapter(value = ["spanColor", "spanPosition", "spanClicks"], requireAll = false)
fun setColorSpan(
    textView: TextView,
    spanColor: Int = Color.BLACK,
    spanPosition: IntArray,
    spanClicks: ArrayList<ClickableSpan>
) {
    val spannableBuilder = SpannableStringBuilder(textView.text)
    var i = 0
    while (i < spanPosition.size) {

        spannableBuilder.setSpan(
            ForegroundColorSpan(spanColor),
            spanPosition[i],
            spanPosition[i + 1],
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
        )

        if (spanClicks.isNotEmpty()) {
            spannableBuilder.setSpan(
                spanClicks[i / 2],
                spanPosition[i],
                spanPosition[i + 1],
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
        }
        i += 2
    }

    textView.movementMethod = LinkMovementMethod.getInstance()
    textView.text = spannableBuilder
    textView.highlightColor = Color.TRANSPARENT
}




